const User = require('./mongo/User');
const Material = require('./mongo/Material');
const Category = require('./mongo/Category');
const Tag = require('./mongo/Tag');
const Transaction = require('./mongo/Transaction');
const Payment = require('./mongo/Payment');
const MaterialOrder = require('./mongo/MaterialOrder');
const Cart = require('./mongo/Cart');

// 用户与资料的关系（上传者）
Material.belongsTo(User, {
  foreignKey: 'uploaderId',
  as: 'uploader'
});
User.hasMany(Material, {
  foreignKey: 'uploaderId',
  as: 'uploadedMaterials'
});

// 资料与分类的关系（多对一）
Material.belongsTo(Category, {
  foreignKey: 'categoryId',
  as: 'category'
});
Category.hasMany(Material, {
  foreignKey: 'categoryId',
  as: 'materials'
});

// 资料与标签的关系（多对多）
const MaterialTag = require('./MaterialTag');
Material.belongsToMany(Tag, {
  through: MaterialTag,
  foreignKey: 'materialId',
  as: 'tags'
});
Tag.belongsToMany(Material, {
  through: MaterialTag,
  foreignKey: 'tagId',
  as: 'materials'
});

// 用户下载记录（多对多）
const Download = require('./Download');
User.belongsToMany(Material, {
  through: Download,
  foreignKey: 'userId',
  as: 'downloadedMaterials'
});
Material.belongsToMany(User, {
  through: Download,
  foreignKey: 'materialId',
  as: 'downloaders'
});

// 用户与交易记录的关系
User.hasMany(Transaction, {
  foreignKey: 'userId',
  as: 'transactions'
});
Transaction.belongsTo(User, {
  foreignKey: 'userId',
  as: 'user'
});

// 素材与交易记录的关系（如果是购买素材）
Material.hasMany(Transaction, {
  foreignKey: 'materialId',
  as: 'transactions'
});
Transaction.belongsTo(Material, {
  foreignKey: 'materialId',
  as: 'material'
});

// 用户与充值记录的关系
User.hasMany(Payment, {
  foreignKey: 'userId',
  as: 'payments'
});
Payment.belongsTo(User, {
  foreignKey: 'userId',
  as: 'user'
});

// 材料订单关联关系
MaterialOrder.belongsTo(User, {
  foreignKey: 'userId',
  as: 'user'
});
User.hasMany(MaterialOrder, {
  foreignKey: 'userId',
  as: 'materialOrders'
});

MaterialOrder.belongsTo(Material, {
  foreignKey: 'materialId',
  as: 'material'
});
Material.hasMany(MaterialOrder, {
  foreignKey: 'materialId',
  as: 'orders'
});

// 材料订单与支付的关联
MaterialOrder.hasOne(Payment, {
  foreignKey: 'materialOrderId',
  as: 'payment'
});
Payment.belongsTo(MaterialOrder, {
  foreignKey: 'materialOrderId',
  as: 'materialOrder'
});